<?php


class SF_SaleOrderService_Helper_Data extends Mage_Core_Helper_Abstract
{
	const WEB_SERVICE_HOST = 'http://127.0.0.1:8080/rumall/services/rumallInterService?wsdl';
	const SHIPPING_TYPE_RUSSIA_ECOMMERCE_EXPRESS 			   = '29';  /*电商专递*/
	const SHIPPING_TYPE_RUSSIA_ECOMMERCE_EXPRESS_DISCOUNT_CODE = '1';   /*电商专递折扣*/
	const SHIPPING_TYPE_REGISTERED_MAIL 					   = '10';  /*小包挂号*/   
	const SHIPPING_TYPE_REGISTERED_MAIL_DISCOUNT_CODE		   = '0'; 	/*小包挂号折扣*/
	
	const SPECIAL_CHAR_OR_LIMITED = '短名称只能是数字、字母、短横线与空格并且不超出35个字符';
	const SKU_IS_NOI_EXIST = 'SKU不存在或者已更改';
	
	protected $init = 0;
	protected $discountInit = 0;
	protected $orderNumberInit = 0;
	protected $customerGroupId;
	protected $error = array();
	protected $hasError = false; 
	
	
	/*
	 * $orderId
	 * $itemData array()
	 * $tradeNo
	 */ 
    public function pushOrderInfo($itemsData)
    {
		Mage::log('分单功能$itemsData信息:',null,'rumall.log');
		Mage::log($itemsData,null,'rumall.log');
		if(is_array($itemsData) && count($itemsData)>0){
			$xmlData = array();
			foreach($itemsData as $itemData){
				$xmlData[] = $this->getValue($itemData);
			}
			
			Mage::log($this->renderRumallXML($xmlData),null,'rumall.log');

			/*如果预分单时有不符合条件的, 则停止分单, 即hasError = ture*/
			if($this->hasError){
				Mage::log('分单报错',1,'rumall.log');
				Mage::log($this->error,1,'rumall.log');
				$res = array();
				foreach($this->error as $key => $skus){
					$res[$key] = implode(',',$skus);
				}
				return $res;
			}else{
				$soap = new SoapClient(self::WEB_SERVICE_HOST);
				if ($this->customerGroupId == '4')
				{
					return $soap->saleOrder($this->renderRumallXML($xmlData),$this->renderUlmartXML($xmlData));
				} else {
					return $soap->saleOrder($this->renderRumallXML($xmlData),"");	/*不给ulmart发报文*/
				}
			}
		}

    }

	

	protected function getValue($itemData)
    {
		$orderId  = $itemData['order_id'];
		$tradeNo  = $itemData['trade_no'];
		$vendorId = $itemData['vendor_id'];
		$items    = $itemData['items'];
    	
    	/* 其他信息 */
		$_order 			= Mage::getModel('sales/order')->load($orderId);
		$this->_order		= $_order;
    	$this->customerGroupId = $_order->getCustomerGroupId();
    	$CurrencyCode		= $_order->getBaseCurrencyCode();
		$PaymentMethod		= $_order->getPayment()->getMethodInstance()->getCode();	/*客户支付方式*/
		$PaymentMethod		= strtoupper(substr($PaymentMethod,0,strpos($PaymentMethod,'_'))); /*截取支付方式*/
		$PayDateTime      	= $_order->getUpdatedAt();
		$Freight			= '0';	/*运费*/

    	/* 收件方信息 */
		$addressInfo		= $_order->getShippingAddress();
		$BuyerId			= $addressInfo->getCustomerId();
		$ReceiverCompany	= $addressInfo->getCompany() ? $addressInfo->getCompany() : 'NIL';
		$ReceiverName 	   	= $addressInfo->getFirstname() .' '. $addressInfo->getMiddlename() .' '. $addressInfo->getLastname(); 
		$ReceiverEmail      = $_order->getCustomerEmail();
		$ConsigneeFullname  = $addressInfo->getFirstname() .' '. $addressInfo->getMiddlename() .' '. $addressInfo->getLastname();
		$ReceiverZipCode    = $addressInfo->getPostcode();
		$ReceiverMobile		= $addressInfo->getTelephone();
		$ReceiverPhone	    = $addressInfo->getTelephone();
		$ReceiverCountry	= Mage::app()->getLocale()->getCountryTranslation($addressInfo->getCountry());
		$ReceiverProvince	= $addressInfo->getRegion() ? $addressInfo->getRegion() : ''; /* 非必填项 */
		$ReceiverCity		= $addressInfo->getCity();
		$Address    		= $addressInfo->getStreetFull();
		$ReceiverAddress 	= $Address .', '
							  . $ReceiverCity .', '
							  . $ReceiverProvince .', '
							  . $ReceiverCountry .', '
							  . $ReceiverZipCode;
							  
		/* 寄件方信息 */		

		$vendorModel 	= Mage::getModel('vendors/vendor')->load($vendorId);
		$CompanyCode 	= $vendorModel->getData('vendor_id');
		$SenderEmail 	= $vendorModel->getData('email');
		$SenderArea  	= '';
		$SenderCompany  = $vendorModel->getData('company');
		$SenderName     = $vendorModel->getData('title');
		$SenderZipCode  = $vendorModel->getData('postcode');
		$SenderZipCode  = mb_substr($SenderZipCode,0,6,"utf-8");
		$SenderMobile   = $vendorModel->getData('telephone');
		$SenderPhone    = $vendorModel->getData('telephone');
		$SenderCountry  = $vendorModel->getData('country_id');
		$SenderProvince = '';              /*寄件方省份*/
		$regionId 		= $vendorModel->getData('region_id');
		$countryId 		= $SenderCountry;
		$data = Mage::getModel('directory/country')
					->setId($countryId)
					->getLoadedRegionCollection();
		foreach($data as $region){
			if($region->getRegionId() == $regionId){
				$SenderProvince = $region->getDefaultName();  /*寄件方省份*/
			}
		}
		$SenderCity 	= $vendorModel->getData('city');
		$SenderAddress  = $vendorModel->getData('address');					  
							  
							  
		/* 物流信息 */
		$shippingMethod	    = $itemData['shipping_type'];
		switch($shippingMethod){
			case '14':
				$shippingMethod = self::SHIPPING_TYPE_RUSSIA_ECOMMERCE_EXPRESS;	/*电商专递*/
				$shippingMethodDiscountCode = self::SHIPPING_TYPE_RUSSIA_ECOMMERCE_EXPRESS_DISCOUNT_CODE;
				break;
			case '16':
				$shippingMethod = self::SHIPPING_TYPE_REGISTERED_MAIL;	/*小包挂号*/
				$shippingMethodDiscountCode = self::SHIPPING_TYPE_REGISTERED_MAIL_DISCOUNT_CODE;
				break;
		}
		$CarrierProduct  = $shippingMethod;
		$Carrier		 = '顺丰速运';
		$DiscountRate	 = Mage::getModel('vendordiscount/vendordiscount')->getCollection()
							->addFieldToFilter('vendor_id', $vendorId)
							->addFieldToFilter('logistics_type', $shippingMethodDiscountCode)
							->getFirstItem()
							->getDiscount(); /*运输类型折扣*/
							
		/* 产品信息 */
		$incrementId     = $_order->getIncrementId();
		$ErpOrder 		 = $incrementId;
		
		
		/*查询最后的一个分单号*/						
		if(!$this->orderNumberInit){
			$subOrderIncrementId = Mage::getModel('saleorderservice/order')->getCollection()
								->addFieldToFilter('increment_id',array('like'=>'%'.$incrementId.'%'))
								->setOrder('increment_id', 'DESC')
								->getFirstItem()
								->getIncrementId();
			if($subOrderIncrementId){
				$this->orderNumberInit = (int)substr($subOrderIncrementId, -3); //截取最后的子订单增长值
				$ordersubnum 	       = $this->orderNumberInit;
				$this->orderNumberInit++;
			}else{
				$ordersubnum = $this->init;
				$this->init++;
			}
		}else{
			$ordersubnum = $this->orderNumberInit;
			$this->orderNumberInit++;
		}
		$ordersubnum 	 = str_pad($ordersubnum + 1,3,"0",STR_PAD_LEFT);
		$OrderTotalAmount= 0;       /*总价格*/
		$OrderDiscount   = 0;		/*总折扣*/
		$UlmartOrderItem = '';
		$OrderItem 		 = '';
		$SaleOrder 		 = array();	//用于存放所有sku的xml报文
		$OrderUrl		 = '';
		
		foreach($items as $item)
		{
			$sku 		 		= $item['sku'];
			$qty 		 		= $item['qty'];
			$orderItemId 		= $item['item_id'];
			
			$_orderItem  		= Mage::getModel('sales/order_item')->load($orderItemId);
			if($_orderItem->getParentItem()) continue;
			$_product           = Mage::getModel('catalog/product')->loadByAttribute('sku',$sku);
			if(!$_product){
				$this->hasError = true;
				$this->error[$sku][] = self::SKU_IS_NOI_EXIST;
				continue;
			}
	 		$ItemOldName 		= $_product->setStoreId(0)->getName();
			$WarehouseCode  	= $_product->getData('common_warehouse_code'); /*仓库编码*/
			$isCharged			= $_product->getData('common_is_charged') ? 'Y' : 'N';
			$itemWeight			= $_orderItem->getWeight();
			$itemBasePrice		= $_orderItem->getBasePrice();
			$itemTotalAmount   	= round($qty * $itemBasePrice, 2);
			$OrderTotalAmount  += $itemTotalAmount;
			/* 
			 * 折扣价格
			 * 计算公式：Item折扣/SKU数量 = 单数量SKU的折扣(如果不整除还有余数，余数加上首个数量上)
			 * 如：
			 * 折扣     = 10USD;
			 * 数量     = 3;
			 * 单个折扣 = 3.33USD;
			 * 余数     = 0.01USD;
			 * 首个折扣 = 3.34USD;
			 */
			$itemDiscount	   = $_orderItem->getBaseDiscountAmount();
			$itemQty		   = $_orderItem->getQtyOrdered();  /* 未分单的item的SKU总数量 */
			$itemDiscountOnce  = floor(($itemDiscount / $itemQty) * 100) / 100; /*单个数量的discount*/
			$discountRemainder = $itemDiscount - round($itemDiscountOnce * $itemQty, 4); /*discount余数*/

			$ItemQuantity	   = $qty;
			if($this->querySkuQtyByIncrementId($sku,$incrementId,$vendorId)){
				$itemTotalDiscount = $itemDiscountOnce * $qty;
				$OrderDiscount    += $itemTotalDiscount;
			}else{
				/* 未分过单，则需要在首单加上余数 */
				if($this->discountInit == 0){
					$itemTotalDiscount = ($itemDiscountOnce * $qty) + $discountRemainder;
					$OrderDiscount    += $itemTotalDiscount;
					$this->discountInit++;
				}else{
					$itemTotalDiscount = $itemDiscountOnce * $qty;
					$OrderDiscount    += $itemTotalDiscount;
				}
			}
			
			
			/*如果该产品是组合产品的子产品，需要获取主产品的url*/
			$configurable_ids   = Mage::getModel('catalog/product_type_configurable')->getParentIdsByChild($_product->getId());
			if(count($configurable_ids) > 0){
				$product_id = $configurable_ids[0];
				$configurationProduct = Mage::getModel('catalog/product')->load($product_id);
				$OrderUrl	= $OrderUrl . $configurationProduct->getProductUrl() .';';
				$short_product_name = $configurationProduct->getData('common_product_name');
				if(!preg_match("/^[a-zA-Z0-9- ]{1,35}$/",$short_product_name)){
					$this->hasError = true;
					$this->error[$sku][] = self::SPECIAL_CHAR_OR_LIMITED;
				}
				
				$attribute_option_id = $_product->getData('common_color');
				$colorText = $_product->setStoreId(0)->setData('common_color', $attribute_option_id)->getAttributeText('common_color');
				if(!empty($colorText) && !empty($_img = $configurationProduct->getMediaGalleryImages()->getItemByColumnValue('label',$colorText)))
				{
					$ItemImage = (string)$_img->getUrl();
				}
				else
				{
					$ItemImage = (string)Mage::helper('catalog/image')->init($configurationProduct, 'image');
				}

			}else{
				$OrderUrl	= $OrderUrl . $_product->getProductUrl() .';';
				$short_product_name = $_product->getData('common_product_name');
				if(!preg_match("/^[a-zA-Z0-9- ]{1,35}$/",$short_product_name)){
					$this->hasError = true;
					$this->error[$sku][] = self::SPECIAL_CHAR_OR_LIMITED;
				}
				$ItemImage = (string)Mage::helper('catalog/image')->init($_product, 'image');
			}


			/**********************拼接报文**********************/
			$OrderItem .= 
				"<OrderItem>
					<SkuNo><![CDATA[{$sku}]]></SkuNo>
					<ItemName><![CDATA[{$short_product_name}]]></ItemName>
					<ItemOldName><![CDATA[{$ItemOldName}]]></ItemOldName>
					<ItemUom>EA</ItemUom>
					<ItemQuantity>{$ItemQuantity}</ItemQuantity>
					<ItemPrice>{$itemBasePrice}</ItemPrice>
					<ItemDiscount>{$itemTotalDiscount}</ItemDiscount>
					<CheckPrepardNo></CheckPrepardNo>
					<CustomsPrepardNo></CustomsPrepardNo>
					<HsCode></HsCode>
					<ItemBrand></ItemBrand>
					<ItemSpecifications></ItemSpecifications>
					<BomAction></BomAction>
					<IsPresent></IsPresent>
					<isCharged>{$isCharged}</isCharged>
					<itemWeight>{$itemWeight}</itemWeight>
					<IsVirtualProduct></IsVirtualProduct>
					<ItemImage><![CDATA[{$ItemImage}]]></ItemImage>
				</OrderItem>
			 ";

			
			/*******************Ulmart的用户还需要拼接发给ulmart的报文*******************/

			if($this->customerGroupId == '4' )
			{
				$itemPrice = Mage::helper('directory')->currencyConvert($itemBasePrice, 'USD', 'RUB'); 
		    	$UlmartOrderItem .= 
		    	"
					<Item>
                         <SkuNo><![CDATA[{$sku}]]></SkuNo>
                         <ItemName><![CDATA[{$_orderItem->getName()}]]></ItemName>
                         <ItemPrice>". round($itemBasePrice,2) ."</ItemPrice>
                         <ItemQuantity>{$ItemQuantity}</ItemQuantity>
                         <PriceSum>". round($itemBasePrice * $ItemQuantity, 2) ."</PriceSum>
                    </Item>
		    	";

			}

		} //end foreach
		
		$CompanyCode = Mage::getModel('vendors/vendor')->load($vendorId)->getVendorId();
		$SaleOrder['rumall'] = 
			"<SaleOrder>
					<VendorId>{$vendorId}</VendorId>
					<CompanyCode>{$CompanyCode}</CompanyCode>
					<WarehouseCode>{$WarehouseCode}</WarehouseCode>
					<RefCode></RefCode>
					<Remark></Remark>
					<FkInsuranceType></FkInsuranceType>
					<SfOrderType>10</SfOrderType>
					<ErpOrder><![CDATA[". $ErpOrder.$ordersubnum ."]]></ErpOrder>
					<OrderNote></OrderNote>
					<TradeOrderDateTime>". $_order->getCreatedAt() ."</TradeOrderDateTime>
					<PayDateTime>{$PayDateTime}</PayDateTime>
					<CurrencyCode>{$CurrencyCode}</CurrencyCode>
					<CompanyNote></CompanyNote>
					<ShopName>Rumall.com</ShopName>
					<TradePlatform></TradePlatform>
					<BuyerId>{$BuyerId}</BuyerId>
					<FromFlag>10</FromFlag>
					<DeliveryDate></DeliveryDate>
					<PaymentMethod>{$PaymentMethod}</PaymentMethod>
					<PaymentNumber>{$tradeNo}</PaymentNumber>
					<Freight>{$Freight}</Freight>
					<DiscountRate>{$DiscountRate}</DiscountRate>
					<OrderTotalAmount><![CDATA[{$OrderTotalAmount}]]></OrderTotalAmount>
					<OrderDiscount>{$OrderDiscount}</OrderDiscount>
					<OtherCharge></OtherCharge>
					<balance_amount></balance_amount>
					<coupons_amount></coupons_amount>
					<gift_card_amount></gift_card_amount>
					<is_appoint_delivery></is_appoint_delivery>
					<appoint_delivery_status></appoint_delivery_status>
					<appoint_delivery_remark></appoint_delivery_remark>
					<is_easy></is_easy>
					<order_url><![CDATA[{$OrderUrl}]]></order_url>
					<order_website>Rumall.com</order_website>
					<isAgent></isAgent>
					<Agent></Agent>
					<AgentService></AgentService>
					<AgentWaybill></AgentWaybill>
					<IsInvoice></IsInvoice>
					<InProcessWaybillNo></InProcessWaybillNo>
					<OrderCarrier>
						<Carrier>{$Carrier}</Carrier>
						<CarrierProduct>{$CarrierProduct}</CarrierProduct>
						<ReturnService>N</ReturnService>
						<cod>N</cod>
						<value_insured>Y</value_insured>
						<declared_value>{$OrderTotalAmount}</declared_value>
					</OrderCarrier>
					<OrderReceiverInfo>
						<ReceiverCompany><![CDATA[{$ReceiverCompany}]]></ReceiverCompany>
						<ReceiverName><![CDATA[{$ReceiverName}]]></ReceiverName>
						<ReceiverEmail><![CDATA[{$ReceiverEmail}]]></ReceiverEmail>
						<ReceiverZipCode><![CDATA[{$ReceiverZipCode}]]></ReceiverZipCode>
						<ReceiverMobile><![CDATA[{$ReceiverMobile}]]></ReceiverMobile>
						<ReceiverPhone><![CDATA[{$ReceiverPhone}]]></ReceiverPhone>
						<CountryCode>MOW</CountryCode>
						<ConsigneeFullname><![CDATA[{$ConsigneeFullname}]]></ConsigneeFullname>
						<ReceiverCountry>RU</ReceiverCountry>
						<ReceiverProvince>Moscow</ReceiverProvince>
						<ReceiverCity>Moscow</ReceiverCity>
						<ReceiverArea></ReceiverArea>
						<ReceiverAddress><![CDATA[{$ReceiverAddress}]]></ReceiverAddress>
						<ConsigneeStreet></ConsigneeStreet>
						<ConsigneeDoorplate></ConsigneeDoorplate>
						<ReceiverIdType></ReceiverIdType>
						<ReceiverIdCard></ReceiverIdCard>
					</OrderReceiverInfo>
					<OrderSenderInfo>
						<from_flag></from_flag>
						<ProvincesCode></ProvincesCode>
						<SenderCompany><![CDATA[{$SenderCompany}]]></SenderCompany>
						<SenderName><![CDATA[{$SenderName}]]></SenderName>
						<SenderEmail><![CDATA[{$SenderEmail}]]></SenderEmail>
						<SenderZipCode><![CDATA[{$SenderZipCode}]]></SenderZipCode>
						<SenderMobile><![CDATA[{$SenderMobile}]]></SenderMobile>
						<SenderPhone><![CDATA[{$SenderPhone}]]></SenderPhone>
						<SenderCountry><![CDATA[{$SenderCountry}]]></SenderCountry>
						<SenderProvince><![CDATA[{$SenderProvince}]]></SenderProvince>
						<SenderCity><![CDATA[{$SenderCity}]]></SenderCity>
						<SenderArea><![CDATA[{$SenderArea}]]></SenderArea>
						<SenderAddress><![CDATA[{$SenderAddress}]]></SenderAddress>
					</OrderSenderInfo>
					<OrderItems>
						{$OrderItem}
					</OrderItems>
				</SaleOrder>
			";
			
			if($this->customerGroupId == '4' ){
				$FreightRUB = Mage::helper('directory')->currencyConvert($Freight, 'USD', 'RUB'); 
				$OrderTotalAmountRUB = Mage::helper('directory')->currencyConvert($OrderTotalAmount, 'USD', 'RUB');
				$ulmartcurrencyCode = 'RUB';
				$orderStatus = 'Processing';
				
				$SaleOrder['ulmart'] = 
		    	"
					<Orders>
					   <CBOrder>". $ErpOrder.$ordersubnum ."</CBOrder>
					   <OrderStatus>{$orderStatus}</OrderStatus>
					   <Erdat>{$PayDateTime}</Erdat>
					   <DeliveryType>02</DeliveryType>
					   <DeliveryPlace>{$ReceiverAddress}</DeliveryPlace>
					   <DeliveryDate>". date('Y-m-d H:i:s',strtotime('+15 day')) ."</DeliveryDate>
					   <DeliveryLog>". round($FreightRUB, 2) ."</DeliveryLog>
					   <DeliverySum>". round($OrderTotalAmountRUB - $FreightRUB, 2) ."</DeliverySum>
					   <DeliveryTotal>". round($OrderTotalAmountRUB, 2) ."</DeliveryTotal>
					   <CurrencyCode>{$ulmartcurrencyCode}</CurrencyCode>
					   <Items>
							{$UlmartOrderItem}
					   </Items>
					</Orders>
		    	";
			}
			
				
		return $SaleOrder; //array
	}//end getValue


	
	protected function renderRumallXML($xmlData)
	{
		$RumallXML = '';
		foreach($xmlData as $data){
			$RumallXML .= $data['rumall'];
		}
		
		$getRumallXML = 
		"<SaleOrderRequest>
				<SaleOrders>
					{$RumallXML}
				</SaleOrders>
			</SaleOrderRequest>
		";
		return $getRumallXML;
	} //end getRumallXML

	protected function renderUlmartXML($xmlData)
	{
		$read 		  = Mage::getSingleton('core/resource')->getConnection('core_read')
						->fetchAll("select ulmart_custid from rumall_ulmart_user where ulmart_user = '"
						. $this->_order->getCustomerEmail() ."'");
		$custid 	  = $read[0]['ulmart_custid'];

		$UlmartXML = '';
		foreach($xmlData as $data){
			$UlmartXML .= $data['ulmart'];
		}
		
		$getUlmartXML = 
		"<UlmartOrder>
		         <CustId>{$custid}</CustId>
				 {$UlmartXML}
			</UlmartOrder>
		";
		return $getUlmartXML;
	} //end getUlmartXML
	
	

	public function querySkuQtyByIncrementId($sku,$incrementId,$vendorId){
		$collection = Mage::getResourceModel("vendorssales/order_collection")
					  ->addFieldToFilter('main_table.vendor_id', $vendorId)
					  ->addFieldToFilter('main_table.increment_id', array('like'=>'%'.$incrementId.'%'))
					  ->addFieldToSelect('entity_id');
		$collection->getSelect()
				   ->joinLeft(array("tsfoi"=>"tb_sales_flat_order_item"),
						"main_table.entity_id = tsfoi.order_id",
						array('tsfoi.sku','tsfoi.qty_ordered')
				   )
				   ->columns(
						array('qty_ordered' => new Zend_Db_Expr('sum(tsfoi.qty_ordered)')
				   ))
				   ->group('tsfoi.sku');
		$data = $collection->getData();
		if($data){
			foreach($data as $v){
				if($v['sku'] == $sku){
					return $v['qty_ordered'];
				}else{
					return false;
				}
			}
		}else{
			return false;
		}
	}
	
	
}//end Class
